package serve.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public class Controller implements IController {

    public HttpServletResponse response;
    public HttpServletRequest request;
    public Map<String, String> params = new HashMap<>();
    public Map<String, Object> data = new HashMap<>();  // 模板渲染的数据

    @Override
    public void Prepare() {

    }

    @Override
    public void Head() {
        common();
    }

    @Override
    public void Get() {
        common();
    }

    @Override
    public void Connect() {
        common();
    }

    @Override
    public void Trace() {
        common();
    }

    @Override
    public void Post() {
        common();
    }

    @Override
    public void Delete() {
        common();
    }

    @Override
    public void Options() {
        common();
    }

    @Override
    public void Copy() {
        common();
    }

    @Override
    public void Link() {
        common();
    }

    @Override
    public void Unlink() {
        common();
    }

    @Override
    public void Finish() {

    }

    @Override
    public void Init(HttpServletRequest request, HttpServletResponse response, Map<String, String> params) {

        this.request = request;
        this.response = response;
        this.params = params;
        this.data = new HashMap<>();
    }

    // 根据参数名获取参数值
    // e.g /index/:uid([0-9]+)/query
    // e.g /index/123/query
    // e.g :uid=123
    public String getParamsByName(String name) {
        StringBuffer sb = new StringBuffer();
        if (!name.startsWith(":")) {
            sb.append(":");
        }
        sb.append(name);

        if (params.containsKey(sb.toString())) {
            return params.get(sb.toString());
        }
        // 返回空值
        return "";
    }

    // 默认处理过程
    private void common() {
        response.setStatus(405);
        try {
            PrintWriter writer = response.getWriter();
            writer.write("Method Not Allowed ");
            writer.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // 判断是否是ajax请求
    public boolean isAjax() {
        return "XMLHttpRequest".equals(request.getHeader("X-Requested-With"));
    }
}
